<template>
  <div class="search-box">
    <el-input
      v-model="searchValue"
      :placeholder="placeholder"
      :prefix-icon="prefixIcon"
      :suffix-icon="suffixIcon"
      :clearable="clearable"
      :size="size"
      @input="handleInput"
      @change="handleChange"
      @clear="handleClear"
      @keyup.enter="handleSearch"
    >
      <el-button
        v-if="showButton"
        slot="append"
        icon="el-icon-search"
        @click="handleSearch"
      ></el-button>
    </el-input>
  </div>
</template>

<script>
export default {
  name: 'SearchBox',
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入搜索内容'
    },
    prefixIcon: {
      type: String,
      default: ''
    },
    suffixIcon: {
      type: String,
      default: 'el-icon-search'
    },
    clearable: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'medium',
      validator: value => ['mini', 'small', 'medium'].includes(value)
    },
    showButton: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchValue: this.value
    }
  },
  watch: {
    value(newVal) {
      this.searchValue = newVal
    },
    searchValue(newVal) {
      this.$emit('input', newVal)
    }
  },
  methods: {
    handleInput(value) {
      this.$emit('input', value)
    },
    handleChange(value) {
      this.$emit('change', value)
    },
    handleClear() {
      this.$emit('clear')
    },
    handleSearch() {
      this.$emit('search', this.searchValue)
    }
  }
}
</script>

<style scoped>
.search-box {
  width: 100%;
}
</style>